import Keys from "../../config/keys";
import Config from "../../config/config";
import RunData from "../../config/RunData";
import {AsyncStorage} from "react-native";
import downloadManifest from "./downloadManifest";
import UtilAes from "../../utils/UtilAes";

/**
 * 拼接url
 */
export default class BaseUrl extends downloadManifest{
    static CONTENT_TYPE = "application/text";
    static CONTENT_TYPE_UPLOAD = "multipart/form-data";

    static HTTP_OK = 1;
    sessionId = RunData.MyUserInfo?RunData.MyUserInfo.sessionId:undefined;
    areaCode = RunData.areaCode;

    POST():Promise{
        return this.url()
            .then((url) => {
                return this.body()
                    .then((body)=>{
                        return fetch(url, {
                            method: "POST",
                            headers: {
                                'Content-Type': this.contentType()
                            },
                            body: body
                        });
                    })
            }).then(response => {
                if (response.ok) {
                    return response.text();
                } else {
                    throw new Error('网路异常');
                }
            }).then(response => {
                return UtilAes.decrypt(response);
            });
    }
    url():Promise {
        var fun = (obj)=>{
            if (obj[this.getParamMethod()]) {
                return obj[this.getParamMethod()];
            } else if (obj.coreservice[this.getParamMethod()]) {
                return obj.coreservice[this.getParamMethod()]
            }
        };
        if(downloadManifest.isFirst){
            return new downloadManifest().GET()
                .then((data)=>{
                    downloadManifest.isFirst = false;
                    return data;
                }).then(fun);
        }else{
            return AsyncStorage.getItem(Keys.downloadMainifest)
                .catch(()=>{//没保存
                    return new downloadManifest().GET()
                })
                .then((data) => {//结果统一
                    if (typeof data == "string") {
                        return JSON.parse(data);
                    } else {
                        return data;
                    }
                })
                .then((obj) => {//取url
                    var url = fun(obj);
                    if(!url){
                        return new downloadManifest().GET()
                            .then(fun)
                    }else{
                        return url;
                    }
                })
        }
    }
    fromUrl():Promise{
        return this.url()
            .then((url)=>{
                var arr = new Array();
                for(var key in this){
                    if(this[key]!=undefined){
                        arr.push(key+"="+this[key])
                    }
                }
                var and = arr.join("&");
                if (url.match(/(#\/)/g)){
                    if (!url.match(/(\?)/g)){
                        url+="?"+and;
                    }else{
                        url+="&"+and;
                    }
                }else if (url.match(/(#)/g)){
                    if (url.match(/(\?)/g)){
                        url = url.replace("#","&"+and+"#");
                    }else{
                        url = url.replace("#","?"+and+"#");
                    }
                }else {
                    if (url.match(/(\?)/g)){
                        url+="&"+and;
                    }else{
                        url=url+"?"+and;
                    }
                }
                return url;
            })
            .then((url)=>{
                return encodeURI(url);
            });
    }
    contentType(){
        return BaseUrl.CONTENT_TYPE;
    }
    body():Promise{
        return new Promise((resolve, reject) => {
            var arr = new Array();
            arr.push("productId=");
            arr.push(Config.productId);
            arr.push("&pltId=");
            arr.push(Config.pltId);
            arr.push("&version=");
            arr.push(Config.version);
            arr.push("&sversion=");
            arr.push(Config.sversion);
            arr.push("&paramMethod=");
            arr.push(this.getParamMethod());
            arr.push("&paramContent=");
            arr.push(JSON.stringify(this));
            resolve(arr.join(''));
        })
            .then((body)=>{
                return UtilAes.encrypt(body);
            });
    }
    getParamMethod(){
        return this.constructor.name;
    }
}